using Nop.Core.Data;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Discounts;
using Nop.Plugin.DiscountRules.Customers.Domain;
using Nop.Services.Customers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nop.Plugin.DiscountRules.Customers.Services
{
	public class RequirementCustomerService:IRequirementCustomerService
	{
		private readonly ICustomerService _customerService;
		private readonly IRepository<RequirementCustomer> _requirementCustomerRepository;

		public RequirementCustomerService(IRepository<RequirementCustomer> discountCustomerRepository,
									   ICustomerService customerService) 
		{
			_customerService = customerService;
			_requirementCustomerRepository = discountCustomerRepository;
		}

		public void AddCustomerToRequirement(int customerId, int discountRequirementId)
		{
			if (GetRequirementCustomer(customerId, discountRequirementId) == null)
			{
				_requirementCustomerRepository.Insert(new RequirementCustomer { 
					RequirementId = discountRequirementId, CustomerId = customerId, CreatedOnUtc = DateTime.UtcNow });				
			}
		}	

		public void RemoveCustomerFromRequirement(int customerId, int discountRequirementId)
		{		
			var requirementCustomer = GetRequirementCustomer(customerId, discountRequirementId);
			if (requirementCustomer != null)
			{
				_requirementCustomerRepository.Delete(requirementCustomer);
			}
		}

		public RequirementCustomer GetRequirementCustomer(int customerId, int discountRequirementId)
		{
			return _requirementCustomerRepository.TableNoTracking
				.FirstOrDefault(rc => rc.CustomerId == customerId && rc.RequirementId == discountRequirementId);
		}

		public IEnumerable<RequirementCustomer> GetRequirementCustomers(int discountRequirementId, int[] customerIds = null)
		{
			return _requirementCustomerRepository.TableNoTracking
			.Where(rc => rc.RequirementId == discountRequirementId && (customerIds == null || customerIds.Contains(rc.CustomerId)));
		}        
	}
}
